﻿using Dapr.Client;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VaccinationHost.Extend;
using VaccinationHost.Model;
using VaccinationHost.Model.ApiArgs;
using VaccinationHost.Model.Dto;
using VaccinationHost.Services;

namespace VaccinationHost.Controllers
{
    /// <summary>
    /// 预约接种控制器
    /// </summary>
    [Route("api/v1/vaccination")]
    [ApiController]
    [Authorize]
    public class VaccinationController : ControllerBase
    {
        private IVaccinationService _vaccinationService;

        public VaccinationController(IVaccinationService vaccinationService)
        {
            this._vaccinationService = vaccinationService;
        }
        /// <summary>
        /// 获取预约接种信息
        /// </summary>
        /// <returns></returns>
        [Route("getvaccinations")]
        [HttpGet]
        public async Task<PaginatedResult<VaccinationDto>> GetVaccinations(VaccinationPageInput pageinout)
        {
            pageinout.FilterByUserId = ClaimData.GetValue(User.Identity.Name).UserId;
            
            return await this._vaccinationService.GetVaccinations(pageinout);
        }

        /// <summary>
        /// 预约登记
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        [Route("appointment")]
        [HttpPost]
        public async Task<ActionResult> Appointment(AppointmentArgs args)
        {
            if (args == null)
            {
                return BadRequest("请求参数异常。");
            }
            if (args.VaccineId==null)
            {
                return BadRequest("请选择疫苗种类。");
            }
            ClaimData claimData = ClaimData.GetValue(User.Identity.Name);
            var result = await _vaccinationService.Appointment(claimData.UserId, args.VaccineId, args.VaccineName, claimData.UserName);

            if (result.Code == 200)
            {
                return Ok();
            }
            else
            {
                return BadRequest(result);
            }
        }

        /// <summary>
        /// 取消预约
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("cancel/{id}")]
        [HttpPut]
        public async Task< ActionResult> Cancel(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return BadRequest("请选择预约记录。");
            }

            // TODO dapr服务地址待定
            using var httpClient = DaprClient.CreateInvokeHttpClient();
            var result = await httpClient.GetAsync("");

            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return Ok();
            }
            else
            {
                var content = await result.Content.ReadAsStringAsync();
                return BadRequest(content);
            }
        }
    }
}
